package com.freedom.sql.jdbc.response;

import java.io.InputStream;
import java.net.Socket;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.sql.jdbc.utils.BufferAllocateUtils;
import com.freedom.sql.jdbc.utils.ByteUtils;
import com.freedom.sql.jdbc.utils.LoggerUtils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.socket.SocketChannel;

public class CommonOkPacket {

	private static final Logger logger = LogManager.getLogger(CommonOkPacket.class);
	private byte[] OK_BYTES = new byte[] { 7, 0, 0, -1, 0, 0, 0, 2, 0, 0, 0 };

	private SocketChannel channel;

	public CommonOkPacket(SocketChannel c, int seq) {
		channel = c;
		OK_BYTES[3] = (byte) seq;
	}

	public void write() {
		// 发送报文
		channel.writeAndFlush(BufferAllocateUtils.get(OK_BYTES.length).writeBytes(OK_BYTES));
	}

	// read
	private Socket socket;
	private byte[] headerBytes = new byte[3];
	byte[] packetNumber = new byte[1];
	byte[] allBytes = null;

	public CommonOkPacket(Socket _socket) {
		this.socket = _socket;
	}

	public byte[] getAllBytes() {
		return allBytes;
	}

	public void setAllBytes(byte[] allBytes) {
		this.allBytes = allBytes;
	}

	public CommonOkPacket read() throws Exception {
		InputStream in = socket.getInputStream();
		// 1)3字节的heaerLength
		in.read(headerBytes, 0, 3);
		int headLength = ByteUtils.littleEndianInteger(headerBytes, 0, 3);
		//LoggerUtils.debug(logger, "length : " + headLength);
		// 2) 1字节的packetNumber
		//LoggerUtils.debug(logger, "try to read packetNumber");
		in.read(packetNumber, 0, 1);
		int packetSeq = ByteUtils.littleEndianInteger(packetNumber, 0, 1);
		//LoggerUtils.debug(logger, "packet Num: " + packetSeq);
		// 3)一次性读取所有字节
		// 一次性读取所有字节
		this.allBytes = new byte[headLength];
		in.read(allBytes, 0, headLength);
		//LoggerUtils.debug(logger, "all content is read done!");		
		return this;
	}

	public ByteBuf toByteBuf() {
		// 开始合成
		ByteBuf finalBuf = BufferAllocateUtils.get(allBytes.length + 4);
		finalBuf.writeBytes(headerBytes);
		finalBuf.writeBytes(packetNumber);
		finalBuf.writeBytes(allBytes);
		return finalBuf;
	}
}
